//
//  HMTabBar.swift
//  Weibo
//
//  Created by 李学林 on 15/12/5.
//  Copyright © 2015年 tete. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {

    var composeButtonClosure:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI();
    }

    // 这个方法在重写init(frame: )方法后就必须实现这个方法 ?
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI(){
        
        addSubview(composeButton)
        
    }
    /// 懒加载控件
    lazy var composeButton :UIButton = {
    
        let button  = UIButton()
        
        // 设置按钮的背景图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button .addTarget(self, action: "centerAddButtonClick", forControlEvents: .TouchUpInside)
        
        button.sizeToFit()
        
        return button
    
    }()
    
    func centerAddButtonClick(){
    
        //printLog("点击了中间的加号按钮")
    
        composeButtonClosure?()
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        composeButton.center = CGPointMake(frame.width * 0.5, frame.height * 0.5)
        
        let subViewWidth = frame.width * 0.2
        
        var index = 0
        
        for subView in subviews{
        
            if subView.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                let x = CGFloat(index) * subViewWidth
                
                subView.frame = CGRectMake(x, 0, subViewWidth, frame.height)
                
                index++
                
                if index == 2 {
                
                    index++
                }
            
            }
        
        }
    }
    
   
    
    // MARK: - 监听事件
    func composeButtonClick(){
        printLog("按钮点击")
        // 执行闭包
        composeButtonClosure?()
    }
    
}
